package com.jeesite.modules.exam.quota.service;

import com.jeesite.common.collect.ListUtils;
import com.jeesite.common.entity.Page;
import com.jeesite.common.idgen.IdGen;
import com.jeesite.common.lang.DateUtils;
import com.jeesite.common.service.CrudService;
import com.jeesite.common.service.ServiceException;
import com.jeesite.common.utils.excel.ExcelImport;
import com.jeesite.modules.backlog.service.DcSupBacklogService;
import com.jeesite.modules.common.service.SysOfficeUnitService;
import com.jeesite.modules.exam.notice.dao.DcSupExamNoticeDao;
import com.jeesite.modules.exam.notice.entity.DcSupExamNotice;
import com.jeesite.modules.exam.notice.service.DcSupExamNoticeService;
import com.jeesite.modules.exam.quota.dao.*;
import com.jeesite.modules.exam.quota.dto.*;
import com.jeesite.modules.exam.quota.entity.*;
import com.jeesite.modules.exam.socreResult.dao.DcSupExamOrgSelectDao;
import com.jeesite.modules.exam.socreResult.entity.DcSupExamOrgSelect;
import com.jeesite.modules.file.utils.FileUploadUtils;
import com.jeesite.modules.sys.entity.DictData;
import com.jeesite.modules.sys.entity.Office;
import com.jeesite.modules.sys.entity.User;
import com.jeesite.modules.sys.service.OfficeService;
import com.jeesite.modules.sys.service.UserService;
import com.jeesite.modules.sys.utils.DictUtils;
import com.jeesite.modules.sys.utils.OfficeUtil;
import com.jeesite.modules.sys.utils.UserUtils;
import com.jeesite.modules.yzw.entity.MsgDetail;
import com.jeesite.modules.yzw.service.LehandYzwPushTask;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
 * 考核任务指标汇总表Service
 * @author xhc
 * @version 2022-06-09
 */
@Service
@Transactional(readOnly=false)
public class DcSupExamSumQuotaInfoService extends CrudService<DcSupExamSumQuotaInfoDao, DcSupExamSumQuotaInfo> {

	@Autowired
	private DcSupExamSumQuotaDao dcSupExamSumQuotaDao;
	@Autowired
	private DcSupExamSumQuotaOrgDao dcSupExamSumQuotaOrgDao;
	@Autowired
	private DcSupExamQuotaDao dcSupExamQuotaDao;
	@Autowired
	private DcSupExamQuotaOrgService dcSupExamQuotaOrgService;

	@Autowired
	private DcSupExamOrgSelectDao selectDao;

	@Resource
	private DcSupExamNoticeDao noticeDao;
	@Resource
	private OfficeService officeService;
	@Resource
	private DcSupExamTargetAuditDao targetAuditDao;
	@Resource
	private DcSupExamQuotaOrgDao dcSupExamQuotaOrgDao;
	@Autowired
	private UserService userService;
	@Autowired
	private LehandYzwPushTask lehandYzwPushTask;
	@Autowired
	private DcSupExamNoticeService dcSupExamNoticeService;
	@Autowired
	private SysOfficeUnitService sysOfficeUnitService;
	@Autowired
	private DcSupBacklogService dcSupBacklogService;
	@Autowired
	private DcSupExamOrgSelectDao dcSupExamOrgSelectDao;
	/**
	 * 获取单条数据
	 * @param dcSupExamSumQuotaInfo
	 * @return
	 */
	@Override
	public DcSupExamSumQuotaInfo get(DcSupExamSumQuotaInfo dcSupExamSumQuotaInfo) {
		return super.get(dcSupExamSumQuotaInfo);
	}
	
	/**
	 * 查询分页数据
	 * @param dcSupExamSumQuotaInfo 查询条件
	 * @param
	 * @return
	 */
	@Override
	public Page<DcSupExamSumQuotaInfo> findPage(DcSupExamSumQuotaInfo dcSupExamSumQuotaInfo) {
		return super.findPage(dcSupExamSumQuotaInfo);
	}
	
	/**
	 * 查询列表数据
	 * @param dcSupExamSumQuotaInfo
	 * @return
	 */
	@Override
	public List<DcSupExamSumQuotaInfo> findList(DcSupExamSumQuotaInfo dcSupExamSumQuotaInfo) {
		return super.findList(dcSupExamSumQuotaInfo);
	}
	
	/**
	 * 保存数据（插入或更新）
	 * @param dcSupExamSumQuotaInfo
	 */
	@Override
	@Transactional(readOnly=false)
	public void save(DcSupExamSumQuotaInfo dcSupExamSumQuotaInfo) {
		super.save(dcSupExamSumQuotaInfo);
		// 保存上传图片
		FileUploadUtils.saveFileUpload(dcSupExamSumQuotaInfo, dcSupExamSumQuotaInfo.getId(), "dcSupExamSumQuotaInfo_image");
		// 保存上传附件
		FileUploadUtils.saveFileUpload(dcSupExamSumQuotaInfo, dcSupExamSumQuotaInfo.getId(), "dcSupExamSumQuotaInfo_file");
	}
	
	/**
	 * 更新状态
	 * @param dcSupExamSumQuotaInfo
	 */
	@Override
	@Transactional(readOnly=false)
	public void updateStatus(DcSupExamSumQuotaInfo dcSupExamSumQuotaInfo) {
		super.updateStatus(dcSupExamSumQuotaInfo);
	}
	
	/**
	 * 删除数据
	 * @param dcSupExamSumQuotaInfo
	 */
	@Override
	@Transactional(readOnly=false)
	public void delete(DcSupExamSumQuotaInfo dcSupExamSumQuotaInfo) {
		super.delete(dcSupExamSumQuotaInfo);
	}

	public Page<ExamQuotaDataDto> queryListData(DcSupExamSumQuotaInfo dcSupExamSumQuotaInfo){
		ExamQuotaDataDto examQuotaDataDto =new ExamQuotaDataDto();
		examQuotaDataDto.setPage(new Page<>(dcSupExamSumQuotaInfo.getPageNo(),dcSupExamSumQuotaInfo.getPageSize()));
		List<ExamQuotaDataDto> result = selectCollectData(dcSupExamSumQuotaInfo);
		examQuotaDataDto.getPage().setCount(result.size());
		return examQuotaDataDto.getPage().setList(result);
	}

	/**
	 * 查询当前机构版本信息
	 * @param dcSupExamSumQuotaInfo
	 * @return
	 */
	public List<VersionInfoDto> queryVersion(DcSupExamSumQuotaInfo dcSupExamSumQuotaInfo){
		List<VersionInfoDto> versions = dao.queryExamVersion(dcSupExamSumQuotaInfo.getExamId(),dcSupExamSumQuotaInfo.getExameOrg(),dcSupExamSumQuotaInfo.getExamYear());
		return versions;
	}

	public List<ExamQuotaDataDto> selectCollectData(DcSupExamSumQuotaInfo dcSupExamSumQuotaInfo){
		//1、 首先查询 考核任务指标汇总表-主表 是否存在已保存版本 存在 则查询 考核任务指标汇总表-主表
		List<ExamQuotaDataDto>  result =null;
		String[] quotaType =null;
		if(!StringUtils.isEmpty(dcSupExamSumQuotaInfo.getQuotaTypes())){
			quotaType =dcSupExamSumQuotaInfo.getQuotaTypes().split(",");
		}
		if(!StringUtils.isEmpty(dcSupExamSumQuotaInfo.getExamYear())){
			String[] split = dcSupExamSumQuotaInfo.getExamYear().split(",");
			dcSupExamSumQuotaInfo.setExamYear(split[0]);
		}
		if(dcSupExamSumQuotaInfo.getVersionNumber()!= null) {
			result = dao.queryExamSumQuotaData(dcSupExamSumQuotaInfo.getExamId(), dcSupExamSumQuotaInfo.getExameOrg(), dcSupExamSumQuotaInfo.getExamYear(), dcSupExamSumQuotaInfo.getVersionNumber(),quotaType,dcSupExamSumQuotaInfo.getQuotaGroup());
		}else{
			// 2 、 不存在 则查询 考核任务指标表-报送-主表
			result = dao.queryExamQuota(dcSupExamSumQuotaInfo.getExamId(),dcSupExamSumQuotaInfo.getExameOrg(),dcSupExamSumQuotaInfo.getExamYear(),null,quotaType,dcSupExamSumQuotaInfo.getQuotaGroup());
		}
//			if (StringUtils.isNotBlank(dcSupExamSumQuotaInfo.getCopyVersion())) {
//				 result = dao.queryExamSumQuotaDataByCopy(dcSupExamSumQuotaInfo.getExamId(), dcSupExamSumQuotaInfo.getExameOrg(), dcSupExamSumQuotaInfo.getExamYear(), dcSupExamSumQuotaInfo.getVersionNumber(),quotaType);
//			    } else {
//					if(dcSupExamSumQuotaInfo.getVersionNumber()!= null) {
//						result = dao.queryExamSumQuotaData(dcSupExamSumQuotaInfo.getExamId(), dcSupExamSumQuotaInfo.getExameOrg(), dcSupExamSumQuotaInfo.getExamYear(), dcSupExamSumQuotaInfo.getVersionNumber(),quotaType);
//					}else{
//						// 2 、 不存在 则查询 考核任务指标表-报送-主表
//						result = dao.queryExamQuota(dcSupExamSumQuotaInfo.getExamId(),dcSupExamSumQuotaInfo.getExameOrg(),dcSupExamSumQuotaInfo.getExamYear(),null,quotaType);
//					}
//		    }

		if (CollectionUtils.isEmpty(result)){
			result =new ArrayList<>();
		}
		// TODO  3、 返回数据按照  关键指标-> 单项指标-> 加减指标 先看实现  排序不行在做处理
		return sortDesc(result);
	}

	/**
	 * 数据排序
	 * @param result
	 */
	private List<ExamQuotaDataDto> sortDesc(List<ExamQuotaDataDto> result) {
		// quota_group  指标类型（1关键指标、2单项指标）   quota_class 指标分类（1.普通指标、2加分项指标、3减分项指标）
		List<ExamQuotaDataDto> list = result.stream()
				.filter(m ->"1".equals(m.getQuotaClass()) && "1".equals(m.getQuotaGroup()))
				.collect(Collectors.toList());
		// 关键指标
		if (CollectionUtils.isEmpty(list)){
			list =new ArrayList<>();
		}
		// 关键指标设置考核评分单位
		list.stream().forEach(s->{
			s.setGradeOrg("241");
			s.setGradeOrgName("市委督查办公室（市政府督查办公室）");
		});

		// 单项指标
		List<ExamQuotaDataDto> quotas=	result.stream()
				.filter(m -> "1".equals(m.getQuotaClass()) && "2".equals(m.getQuotaGroup()))
				.collect(Collectors.toList());
		// 加项指标
		List<ExamQuotaDataDto> add_quotas=	result.stream()
				.filter(m -> "2".equals(m.getQuotaClass()))
				.collect(Collectors.toList());
		// 减项指标
		List<ExamQuotaDataDto> sub_quotas=	result.stream()
				.filter(m -> "3".equals(m.getQuotaClass()))
				.collect(Collectors.toList());
		// 指标汇总添加
		list.addAll(Optional.ofNullable(quotas).orElseGet(()->new ArrayList<>()));
		list.addAll(Optional.ofNullable(add_quotas).orElseGet(()->new ArrayList<>()));
		list.addAll(Optional.ofNullable(sub_quotas).orElseGet(()->new ArrayList<>()));
		return list;
	}


	public Page<DcSupExamSumQuotaInfo> findKeyPage(DcSupExamSumQuotaInfo dcSupExamSumQuotaInfo) {
		Page<DcSupExamSumQuotaInfo> page = dcSupExamSumQuotaInfo.getPage();
		List<DcSupExamSumQuotaInfo>   list = dao.findKeyPageList(dcSupExamSumQuotaInfo);
		page.setList(list);
		return page;
	}

	public Page<DcSupExamSumQuotaInfo> findDanPage(DcSupExamSumQuotaInfo dcSupExamSumQuotaInfo) {
		Page<DcSupExamSumQuotaInfo> page = dcSupExamSumQuotaInfo.getPage();
		List<DcSupExamSumQuotaInfo>   list = dao.findDanPageList(dcSupExamSumQuotaInfo);
		page.setList(list);
		return page;
	}
	@Transactional(readOnly=false)
	public void saveStrList(List<DcSupExamSumQuotaInfo> dcSupExamSumQuotaInfos) {
		dcSupExamSumQuotaInfos.forEach(info->{
			info.setQuotaType(null);
			info.setFileStatus("2");
			super.save(info);
			FileUploadUtils.saveFileUpload(info.getId(), "dcSupExamSumQuotaInfo_file", info.getFileuploadId(), "");
		});

	}

	/**
	 * 生成副本数据
	 * @param dcSupExamSumQuotaInfo
	 */
	@Transactional(readOnly=false)
	public void makeCopy(DcSupExamSumQuotaInfo dcSupExamSumQuotaInfo) {
		//查询最大版本号
		String versionNumber= dcSupExamSumQuotaDao.queryMaxVersionByExamId(dcSupExamSumQuotaInfo.getExamId());
		Map<String, List<DcSupExamOrgSelect>> orgSelects = selectDao.findList(new DcSupExamOrgSelect()).stream().collect(Collectors.groupingBy(DcSupExamOrgSelect::getOrgCode));
		if(StringUtils.isBlank(dcSupExamSumQuotaInfo.getCopyVersion())) {
			List<ExamQuotaCopyDto> list = dcSupExamQuotaDao.queryQuotaByExamId(dcSupExamSumQuotaInfo.getExamId());
			//创建主版本1号，
			DcSupExamSumQuota ta = new DcSupExamSumQuota();
			ta.setId(IdGen.nextId());
			ta.setVersionNumber(StringUtils.isBlank(versionNumber) ? 1L : Long.parseLong(versionNumber) + 1);
			ta.setVersionName("指标_副本" + ta.getVersionNumber());
			ta.setSumStatus("0");
			ta.setRemarks4(0 + "");
			ta.setExamId(dcSupExamSumQuotaInfo.getExamId());
			ta.setCreateBy(UserUtils.getUser().getUserCode());
			ta.setCreateDate(new Date());
			dcSupExamSumQuotaDao.insert(ta);
			for (ExamQuotaCopyDto dto : list) {
				DcSupExamSumQuotaInfo info = new DcSupExamSumQuotaInfo();
				BeanUtils.copyProperties(dto, info);
				info.setId(IdGen.nextId());
				info.setQuotaWeight(dto.getQuotaWeight());
				info.setSumQuotaId(ta.getId());
				info.setQuotaInfoId(dto.getId());
				// 备注
				info.setRemarks(dto.getOrgRemarks());
				// 区县类型
				if (StringUtils.isEmpty(dto.getOrgType())) {
					if (orgSelects.containsKey(dto.getExameOrg())) {
						info.setOrgType(orgSelects.get(dto.getOrgType()).get(0).getOrgType());
					}
				}
				if (StringUtils.equals(dto.getQuotaGroup(), "2")) {
					DcSupExamSumQuotaOrg org = new DcSupExamSumQuotaOrg();
					org.setSumQuotaId(info.getId());
					String id = IdGen.nextId();
					org.setId(id);
					org.setSumQuotaId(info.getId());
					org.setGradeOrg(dto.getCreateOrg());
					org.setGradeOrgName(dto.getCreateOrgName());
					dcSupExamSumQuotaOrgDao.insert(org);
				}
				info.setFileStatus("1");
				dao.insert(info);
			}
		}
		//后期需要版本副本概念   放开此处代码即可
//		}else{
//
//			//通过examId和remark4中存版本copy有没有存在,存在不管,不存在生成副本数据;
//			Integer copyVerison =  dao.queryCopyVersionByExamIdRemark4(dcSupExamSumQuotaInfo);
//			if(copyVerison < 1){
//				DcSupExamSumQuota ta =  dao.queryVerisonByExamIdVersion(dcSupExamSumQuotaInfo);
//				dcSupExamSumQuotaInfo.setSumQuotaId(ta.getId());
//				List<DcSupExamSumQuotaInfo> list = dao.findList(dcSupExamSumQuotaInfo);
//				ta.setId(IdGen.nextId());
//				ta.setRemarks4(dcSupExamSumQuotaInfo.getCopyVersion());
//				ta.setVersionNumber(Long.parseLong(versionNumber)+1);
//				ta.setVersionName(ta.getVersionName()+"_副本");
//				ta.setSumStatus("0");
//				dcSupExamSumQuotaDao.insert(ta);
//				for(DcSupExamSumQuotaInfo x:list){
//					String sumQuotaId= x.getId();
//					x.setId(null);
//					x.setSumQuotaId(ta.getId());
//					x.setFileStatus("1");
//					dao.insert(x);
//					DcSupExamSumQuotaOrg org =	new DcSupExamSumQuotaOrg();
//					org.setSumQuotaId(sumQuotaId);
////					String id =IdGen.nextId();
//					List<DcSupExamSumQuotaOrg> list1 = dcSupExamSumQuotaOrgDao.findList(org);
//					if(list1 != null && list1.size()>0){
//						List<DcSupExamSumQuotaOrg> collect = list1.stream().peek(p -> p.setSumQuotaId(x.getId())).peek(p->p.setId(null)).collect(Collectors.toList());
//						System.out.println(collect.toString());
//						dcSupExamSumQuotaOrgDao.insertBatch(collect);
//					}
//
//				}
//			}
//		}


	}
	@Transactional(readOnly=false)
	public void saveStrSumList(List<DcSupExamSumQuotaInfo> dcSupExamSumQuotaInfos) {
		// 查询出修改前的数据信息
		Map<String, List<DcSupExamSumQuotaInfo>> listMap = findAllQuotaInfos(dcSupExamSumQuotaInfos);


		dcSupExamSumQuotaInfos.stream().filter(k->k.getId()!=null).forEach(info->{
			info.setFileStatus("1");
			if ("2".equals(info.getQuotaGroup())){
				if (listMap.containsKey(info.getId())){
					DcSupExamSumQuotaInfo oldInfo = listMap.get(info.getId()).get(0);
					// 对比数据是否做修改  指标类别  目标类容 和 考核评分单位
					if (!oldInfo.getQuotaType().equals(info.getQuotaType()) ||
						!oldInfo.getQuotaContent().equals(info.getQuotaContent()) ||
						(!StringUtils.isEmpty(oldInfo.getGradeOrg()) && (!oldInfo.getGradeOrg().equals(info.getGradeOrg())))
					){
						info.setQuotaInfoId(IdGen.nextId());
					}
				}
			}
			// 修改指标类型时需要进行处理 因为存在着修改的可能
			// 查询所有指标类别
			DictData dc_quotaType = DictUtils.getDictData("dc_quotaType", info.getQuotaType());
			// 减分项
			if ("13".equals(dc_quotaType.getDictValue())){
				info.setQuotaClass("3");
				info.setQuotaGroup("2");
			// 加分项
			}else if ("14".equals(dc_quotaType.getDictValue())){
				info.setQuotaClass("2");
				info.setQuotaGroup("2");
			// 单项
			}else if ("11".equals(dc_quotaType.getDictValue())){
				info.setQuotaClass("1");
				info.setQuotaGroup("2");
			// 关键
			}else{
				info.setQuotaClass("1");
				info.setQuotaGroup("1");
			}
			super.save(info);
		});
		if (!CollectionUtils.isEmpty(dcSupExamSumQuotaInfos)) {
			// 保存 新增指标 和 考核评分单位数据信息
			Map<String, String> gradeCodes = dcSupExamSumQuotaInfos.stream()
					.filter(m -> m.getGradeOrg() != null && !m.getGradeOrg().equals("|") && m.getId() != null)
					.collect(Collectors.toMap(DcSupExamSumQuotaInfo::getId, DcSupExamSumQuotaInfo::getGradeOrg));
			gradeCodes.forEach((k,v)->{
				if (!StringUtils.isEmpty(v)){
					String[] strings = v.split("\\|");
					DcSupExamSumQuotaOrg quotaOrg = dcSupExamSumQuotaOrgDao.queryOrg(k);
					if (quotaOrg ==null){
						quotaOrg =new DcSupExamSumQuotaOrg();
						quotaOrg.setSumQuotaId(k);
						quotaOrg.setGradeOrg(strings[0]);
						quotaOrg.setGradeOrgName(strings[1]);
						dcSupExamSumQuotaOrgDao.insert(quotaOrg);
					}else{
						quotaOrg.setGradeOrg(strings[0]);
						quotaOrg.setGradeOrgName(strings[1]);
						dcSupExamSumQuotaOrgDao.update(quotaOrg);
					}
				}
			});
			// 防止没有sum_quota_id 进行添加操作导致报错情况
			List<DcSupExamSumQuotaInfo>  noEmptys = dcSupExamSumQuotaInfos.stream().filter(m -> m.getSumQuotaId() != null).collect(Collectors.toList());
			if (CollectionUtils.isEmpty(noEmptys)){
				return;
			}
			// 新增指标 执行插入
			List<DcSupExamSumQuotaInfo> newInsert = dcSupExamSumQuotaInfos.stream()
					.filter(m -> m.getId() == null)
					.collect(Collectors.toList());
			String sumQuotaId = noEmptys.get(0).getSumQuotaId();

			Map<String, List<DcSupExamOrgSelect>> orgSelects = selectDao.findList(new DcSupExamOrgSelect()).stream().collect(Collectors.groupingBy(DcSupExamOrgSelect::getOrgCode));
			for (int i = 0; i < newInsert.size(); i++) {
				DcSupExamSumQuotaInfo quotaInfo = newInsert.get(i);
				quotaInfo.setQuotaInfoId(IdGen.nextId());
				if (quotaInfo.getType().equals("1")){
						quotaInfo.setQuotaClass("1");
						quotaInfo.setQuotaGroup("2");
				}else if (quotaInfo.getType().equals("2")){
					quotaInfo.setQuotaClass("1");
					quotaInfo.setQuotaGroup("1");
				}else if (quotaInfo.getType().equals("3")){
					quotaInfo.setQuotaClass("2");
					quotaInfo.setQuotaGroup("2");
				}else if (quotaInfo.getType().equals("4")){
					quotaInfo.setQuotaClass("3");
					quotaInfo.setQuotaGroup("2");
				}
				if (orgSelects.containsKey(quotaInfo.getExameOrg())){
				    quotaInfo.setOrgType(orgSelects.get(quotaInfo.getExameOrg()).get(0).getOrgType());
				}
				String examYear = quotaInfo.getExamYear();
				quotaInfo.setExamYear(examYear.split(",")[0]);
				quotaInfo.setFileStatus("1");
				quotaInfo.setSumQuotaId(sumQuotaId);
				quotaInfo.setCreateDate(new Date());
				super.save(quotaInfo);
				// 进行 考核任务指标汇总表-牵头评分单位数据插入
				if (quotaInfo.getGradeOrg() == null || quotaInfo.getGradeOrg().equals("|") ) {
					continue;
				}
				String[] strings = quotaInfo.getGradeOrg().split("\\|");
				DcSupExamSumQuotaOrg save =new DcSupExamSumQuotaOrg();
				save.setSumQuotaId(quotaInfo.getId());
				save.setGradeOrgName(strings[1]);
				save.setGradeOrg(strings[0]);
				dcSupExamSumQuotaOrgDao.insert(save);
			}
		}
	}


	private Map<String,List<DcSupExamSumQuotaInfo>> findAllQuotaInfos(List<DcSupExamSumQuotaInfo> dcSupExamSumQuotaInfos){
		List<String> ids = dcSupExamSumQuotaInfos.stream().filter(k -> k.getId() != null).map(s -> s.getId()).collect(Collectors.toList());
		if (CollectionUtils.isEmpty(ids)){
			return null;
		}
		List<DcSupExamSumQuotaInfo> old= dao.queryExamQuotaInfoByIds(ids);
		Map<String, List<DcSupExamSumQuotaInfo>> result = old.stream().collect(Collectors.groupingBy(DcSupExamSumQuotaInfo::getId));
		return result;
	}

	@Transactional(readOnly=false)
	public String saveVersion(DcSupExamSumQuota dcSupExamSumQuota) {
		List<DcSupExamSumQuota> versionName = dcSupExamSumQuotaDao.queryVersionNameIsExits(dcSupExamSumQuota);
		if (!CollectionUtils.isEmpty(versionName)) {
			return "99999999";
		}
		//查询最大版本号
		String versionNumber = dcSupExamSumQuotaDao.queryMaxVersionByExamId(dcSupExamSumQuota.getExamId());
		DcSupExamSumQuota ta = null;
		// 需要版本副本操作  打开注释即可
//		if ( StringUtils.isEmpty(dcSupExamSumQuota.getRemarks2())) {
//			createVersion(dcSupExamSumQuota,versionNumber);
//		} else {
//			ta = dao.queryExamQuotaCopyVersion(dcSupExamSumQuota, "0");
//			ta.setVersionName(dcSupExamSumQuota.getVersionName());
//			ta.setSumStatus("1");
//			dcSupExamSumQuotaDao.update(ta);
//		}
		String version = createVersion(dcSupExamSumQuota, versionNumber);
		return version;
	}

	private String createVersion(DcSupExamSumQuota dcSupExamSumQuota,String versionNumber){
		Map<String, List<DcSupExamOrgSelect>> orgSelects = selectDao.findList(new DcSupExamOrgSelect()).stream().collect(Collectors.groupingBy(DcSupExamOrgSelect::getOrgCode));
		// 版本号为空时 为初始版本 否则为指定版本数据信息
		StringBuffer sb =new StringBuffer();
		if (dcSupExamSumQuota.getVersionNumber() == null){
			List<ExamQuotaCopyDto>	list = dcSupExamQuotaDao.queryQuotaByExamId(dcSupExamSumQuota.getExamId());
			//创建主版本1号，
			DcSupExamSumQuota ta = new DcSupExamSumQuota();
			ta.setId(IdGen.nextId());
			ta.setVersionNumber(StringUtils.isBlank(versionNumber)?1L:Long.parseLong(versionNumber)+1);
			ta.setVersionName(dcSupExamSumQuota.getVersionName());
			ta.setSumStatus("1");
			ta.setRemarks4("0");
			ta.setExamId(dcSupExamSumQuota.getExamId());
			ta.setCreateBy(UserUtils.getUser().getUserCode());
			ta.setCreateDate(new Date());
			dcSupExamSumQuotaDao.insert(ta);
			sb.append(ta.getVersionNumber());
			for(ExamQuotaCopyDto dto: list){
				DcSupExamSumQuotaInfo info = new DcSupExamSumQuotaInfo();
				BeanUtils.copyProperties(dto,info);
				info.setId(IdGen.nextId());
				info.setQuotaWeight(dto.getQuotaWeight());
				info.setSumQuotaId(ta.getId());
				info.setQuotaInfoId(dto.getId());
				// 区县类型
				if (StringUtils.isEmpty(dto.getOrgType())){
					if (orgSelects.containsKey(dto.getExameOrg())){
						info.setOrgType(orgSelects.get(dto.getOrgType()).get(0).getOrgType());
					}
				}
				if(StringUtils.equals(dto.getQuotaGroup(),"2")){
					DcSupExamSumQuotaOrg org =	new DcSupExamSumQuotaOrg();
					org.setSumQuotaId(info.getId());
					String id =IdGen.nextId();
					org.setId(id);
					org.setSumQuotaId(info.getId());
					org.setGradeOrg(dto.getCreateOrg());
					org.setGradeOrgName(dto.getCreateOrgName());
					dcSupExamSumQuotaOrgDao.insert(org);
				}
				if(StringUtils.equals(dto.getQuotaGroup(),"1")){
					DcSupExamSumQuotaOrg org =	new DcSupExamSumQuotaOrg();
					org.setSumQuotaId(info.getId());
					String id =IdGen.nextId();
					org.setId(id);
					org.setSumQuotaId(info.getId());
					org.setGradeOrg("263");
					org.setGradeOrgName("市政府办公室");
					dcSupExamSumQuotaOrgDao.insert(org);
				}
				info.setFileStatus("1");
				dao.insert(info);
			}
		}else{
			DcSupExamSumQuotaInfo examSumQuotaInfo =new DcSupExamSumQuotaInfo();
			// 考核任务id
			examSumQuotaInfo.setExamId(dcSupExamSumQuota.getExamId());
			examSumQuotaInfo.setVersionNumber(dcSupExamSumQuota.getVersionNumber());
			// 用作查询
			examSumQuotaInfo.setCopyVersion(dcSupExamSumQuota.getVersionNumber()+"");

			DcSupExamSumQuota ta =  dao.queryVerisonByExamIdVersion(examSumQuotaInfo);
			examSumQuotaInfo.setSumQuotaId(ta.getId());
			List<DcSupExamSumQuotaInfo> list = dao.findList(examSumQuotaInfo);
			ta.setId(IdGen.nextId());
			ta.setRemarks4(examSumQuotaInfo.getVersionNumber()+"");
			ta.setVersionNumber(Long.parseLong(versionNumber)+1);
			ta.setVersionName(dcSupExamSumQuota.getVersionName());
			ta.setCreateDate(new Date());
			ta.setCreateBy(UserUtils.getUser().getUserCode());
			ta.setSumStatus("1");
			dcSupExamSumQuotaDao.insert(ta);
			sb.append(ta.getVersionNumber());
			for(DcSupExamSumQuotaInfo x:list){
				String sumQuotaId= x.getId();
				x.setId(null);
				x.setSumQuotaId(ta.getId());
				x.setFileStatus("1");
				dao.insert(x);
				DcSupExamSumQuotaOrg org =	new DcSupExamSumQuotaOrg();
				org.setSumQuotaId(sumQuotaId);
				List<DcSupExamSumQuotaOrg> list1 = dcSupExamSumQuotaOrgDao.findList(org);
				if(list1 != null && list1.size()>0){
					List<DcSupExamSumQuotaOrg> collect = list1.stream().peek(p -> p.setSumQuotaId(x.getId())).peek(p->p.setId(null)).collect(Collectors.toList());
					dcSupExamSumQuotaOrgDao.insertBatch(collect);
				}
			}
		}
		return sb.toString();
	}

	@Transactional(readOnly=false)
	public String publish(DcSupExamSumQuota dcSupExamSumQuota) {
		// 如果当前版本已存在发布  则不允许再次发布
		Integer queryIsPublish = dcSupExamSumQuotaDao.queryIsPublish(dcSupExamSumQuota.getExamId(),dcSupExamSumQuota.getVersionNumber(), "2");
		if (queryIsPublish >0){
			return "当前版本已发布";
		}
		// 查询是否发送细则通知
		DcSupExamNotice noticeDaoList = noticeDao.getNoticeByExamId(dcSupExamSumQuota.getExamId(),"5");
		if (noticeDaoList !=null){
			return "当前任务已发布细则通知,不允许再次发布";
		}
		// 需要对数据做校验处理
//		List<ExamQuotaDataDto> quotaDataDtos = dao.queryExamSumQuotaData(dcSupExamSumQuota.getExamId(), null, null, dcSupExamSumQuota.getVersionNumber(), null);
		String isRange= checkScoreRange(dcSupExamSumQuota);
		if ("00000".equals(isRange)){
			return "当前任务指标数为空，不允许发布版本";
		}
		if (isRange.length()>18){
			return isRange;
		}
		//查询最大版本号
		String versionNumber= dcSupExamSumQuotaDao.queryMaxVersionByExamId(dcSupExamSumQuota.getExamId());
		DcSupExamSumQuota ta  =null;
		if(dcSupExamSumQuota.getVersionNumber()==null){
			dcSupExamSumQuota.setVersionNumber(Long.parseLong(versionNumber));
			ta  = dao.queryExamQuotaCopy(dcSupExamSumQuota);
		}else{
//			ta  = dao.queryExamQuotaCopyVersion(dcSupExamSumQuota,"0");
			List<DcSupExamSumQuota> quota = dcSupExamSumQuotaDao.findList(dcSupExamSumQuota);
			if (!CollectionUtils.isEmpty(quota) && quota.get(0).getSumStatus().equals("2")){
				return "当前版本已发布";
			}
			ta = dao.queryPublish(dcSupExamSumQuota);
		}
		dcSupExamSumQuotaDao.updatePublishVersion(dcSupExamSumQuota);

		ta.setSumStatus("2");
		dcSupExamSumQuotaDao.update(ta);
		return "9";
	}

	public Integer isPush(String examId, String s) {
		Integer queryIsPublish = dcSupExamSumQuotaDao.queryIsPublish(examId,null, s);
		return queryIsPublish;
	}

	/**
	 * 检查发布版本的权数是否超过规定值
	 * @return
	 */
	public String checkScoreRange(DcSupExamSumQuota dcSupExamSumQuota){
		// 进行添加前预处理
		StringBuffer sp =new StringBuffer("当前机构以下[");
	    // 统计指标为0的数据信息
        List<Map<String,String>> counts= dcSupExamSumQuotaDao.countQuotaInfoByZero(dcSupExamSumQuota.getExamId(), dcSupExamSumQuota.getVersionNumber());
		if (!CollectionUtils.isEmpty(counts)){
			for (int i = 0; i < counts.size(); i++) {
				 Map<String, String> map = counts.get(i);
				String examorgName =  map.get("name");
				// 条数
				Object score2= map.get("nums");
				Long addScore=0L;
				if (score2 instanceof Long){
					addScore = (Long) score2;
				}
				sp.append("["+examorgName + "]机构存在指标权数为0的共计:(" + addScore + ")条;");
			}
		}
		if (sp.toString().length()> 18){
			return sp.toString();
		}
		// 加分项
		List<Map<String,String>> 	quotaInfos = dcSupExamSumQuotaDao.groupByOrgSumWeigth(dcSupExamSumQuota.getExamId(), dcSupExamSumQuota.getVersionNumber(),"2");
		// 单项+关键
		List<Map<String,String>> 	scoreAdd = dcSupExamSumQuotaDao.groupByOrgSumWeigth(dcSupExamSumQuota.getExamId(), dcSupExamSumQuota.getVersionNumber(),"1");

		if (CollectionUtils.isEmpty(quotaInfos) && CollectionUtils.isEmpty(scoreAdd)){
			return "00000";
		}

		for (int i = 0; i < quotaInfos.size(); i++) {
			Map<String, String> map = quotaInfos.get(i);
			// 机构代码
			String examorgName =  map.get("examOrgName");
			// 分数
			Object score2= map.get("score");
			Double addScore=0.0;
			if (score2 instanceof BigDecimal){
				BigDecimal add = (BigDecimal) score2;
				addScore = add.doubleValue();
			}
			if (addScore > 3) {
				sp.append(examorgName + "当前加分权重添加前总分数为:(" + addScore + ")分");
			}
		}


		for (int i = 0; i < scoreAdd.size(); i++) {
			Map<String, String> map = scoreAdd.get(i);
			// 机构类型
			String orgtype = map.get("orgType");
			// 机构代码
			String examorgName =  map.get("examOrgName");
			// 分数
			Object score2= map.get("score");
			Double addScore=0.0;
			if (score2 instanceof BigDecimal){
				BigDecimal add = (BigDecimal) score2;
				addScore = add.doubleValue();
			}
			if ("1".equals(orgtype) && addScore > 150) {
				sp.append(examorgName + "[区县]当前权数总分数为:(" + addScore + ")分");
			} else if ("2".equals(orgtype) && addScore > 100) {
				sp.append(examorgName + "[市直]当前权数总分数为:(" + addScore + ")分");
			}

		}
		sp.append("]");
		return sp.toString();
	}

	/**
	 * 指标汇总，数据导出
	 * @param dcSupExamSumQuotaInfo
	 * @param request
	 * @param response
	 */
	public void export(DcSupExamSumQuotaInfo dcSupExamSumQuotaInfo, HttpServletRequest request, HttpServletResponse response) {
		// 获取excel表头
		List<String> headerList = dcSupExamSumQuotaInfo.getExportColumn();
		// 检查用户是否没有选列
		if (checkHeaderList(headerList)) {
			// 查询左侧被考核单位
			List<DcSupExamQuotaOrg> list = dcSupExamQuotaOrgService.findOrgByExamId(dcSupExamSumQuotaInfo.getExamId());
			if (CollectionUtils.isEmpty(list)) {
				return;
			}

			// 检查用户是否选择了【只导出关键指标】
			if (headerList.contains("onlyGuanJian") && !headerList.contains("onlyDanXiang")) {
				dcSupExamSumQuotaInfo.setQuotaGroup("1");
			}
			// 检查用户是否选择了【只导出单项指标】
			if (headerList.contains("onlyDanXiang") && !headerList.contains("onlyGuanJian")) {
				dcSupExamSumQuotaInfo.setQuotaGroup("2");
			}

			// 构造结果集
			Map<String, List<ExamQuotaDataDto>> result = new LinkedHashMap<>();
			// 依次查询所有的被考核单位
			for (int i = 0; i < list.size(); i++) {
				DcSupExamQuotaOrg examQuotaOrg = list.get(i);
				dcSupExamSumQuotaInfo.setExameOrg(examQuotaOrg.getExameOrg());
				// 查询当前被考核单位的所有指标
				List<ExamQuotaDataDto> collectData = selectCollectData(dcSupExamSumQuotaInfo);
				if (CollectionUtils.isEmpty(collectData)) {
					continue;
				}
				result.put(examQuotaOrg.getExameOrg() + "|" + examQuotaOrg.getExameOrgName(), collectData);
			}
			if (result.isEmpty()) {
				return;
			}
			// 将需要导出的数据装载
			downLoadInfo(result, headerList, request, response);
		}
	}

	/**
	 * 判断传入的导出列是否为空
	 * @param headerList
	 * @return
	 */
	private Boolean checkHeaderList(List<String> headerList) {
		if (headerList != null && headerList.size() != 0) {
			int tempLength = headerList.size();
			// 先把类型选择删掉
			if (headerList.contains("onlyGuanJian")) {
				tempLength--;
			}
			if (headerList.contains("onlyDanXiang")) {
				tempLength--;
			}
			// 判断是否有导出列
			return tempLength > 0;
		} else {
			return false;
		}
	}

	/**
	 * 将需要导出的数据装载到excel中
	 * @param result 数据
	 * @param headerList 可选表头
	 * @param request
	 * @param response
	 */
	private void downLoadInfo(Map<String, List<ExamQuotaDataDto>> result,List<String> headerList,HttpServletRequest request, HttpServletResponse response) {
		// 获取表头
		List<String> header = getHeaderByHeaderList(headerList);
		HSSFWorkbook workbook = new HSSFWorkbook();

		// 设置单元格样式
		CellStyle cellStyle = workbook.createCellStyle();
		// 水平居中
		cellStyle.setAlignment(HorizontalAlignment.CENTER);
		// 垂直居中
		cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
		// 设置四边边框
		cellStyle.setBorderBottom(BorderStyle.THIN);
		cellStyle.setBorderLeft(BorderStyle.THIN);
		cellStyle.setBorderRight(BorderStyle.THIN);
		cellStyle.setBorderTop(BorderStyle.THIN);
		// 自动换行
		cellStyle.setWrapText(true);
		// 字体
		Font dataFont = workbook.createFont();
		dataFont.setFontName("宋体");
		// 字体大小
		dataFont.setFontHeightInPoints((short) 11);
		cellStyle.setFont(dataFont);

		try {
			OutputStream out = response.getOutputStream();

			String fileName = "指标汇总导出-" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
			//定义标题以及设置响应头信息
			response.setCharacterEncoding("UTF-8");
			response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName + ".xls", "UTF-8"));
			response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");

			result.forEach((k, v) -> {
				// 用被考核单位名称作为sheet页名称
				String[] split = k.split("\\|");
				HSSFSheet sheet = workbook.createSheet(split[1]);
				// 创建标题行
				HSSFRow sheetRow = sheet.createRow(0);
				// 行高
				sheetRow.setHeight((short) (30 * 20));
				// 设置列宽
				for (int i = 0; i < header.size(); i++) {
					if ("目标内容".equals(header.get(i))) {
						// 设置宽度
						sheet.setColumnWidth(i, 50 * 256);
					} else {
						sheet.setColumnWidth(i, 16 * 256);
					}
					HSSFCell cell = sheetRow.createCell(i);
					cell.setCellValue(header.get(i));
					cell.setCellStyle(cellStyle);
				}

				// 数据填充
				List<ExamQuotaDataDto> quotaDataDtoList = v;

				for (int i = 0; i < quotaDataDtoList.size(); i++) {
					HSSFRow row = sheet.createRow(i + 1);
					// 设置行高
					row.setHeight((short) (28 * 20));
					ExamQuotaDataDto quotaDataDto = quotaDataDtoList.get(i);

					// 定义临时变量记录列号
					int index = 0;

					// 被考核单位
					HSSFCell cell1 = row.createCell(index++);
					cell1.setCellStyle(cellStyle);
					cell1.setCellValue(split[1]);

					// 指标类别 暂未处理
					if (headerList.contains("quotaType")) {
						HSSFCell cell2 = row.createCell(index++);
						cell2.setCellStyle(cellStyle);
						DictData dc_quotaType = DictUtils.getDictData("dc_quotaType", quotaDataDto.getQuotaType());
						if (dc_quotaType != null && dc_quotaType.getDictLabel() != null) {
							cell2.setCellValue(dc_quotaType.getDictLabel());
						}
					}

					// 序号
					if (headerList.contains("sortNum")) {
						HSSFCell cell3 = row.createCell(index++);
						if (quotaDataDto.getSortNum() != null) {
							cell3.setCellValue(quotaDataDto.getSortNum());
						}
						cell3.setCellStyle(cellStyle);
					}

					// 目标内容
					if (headerList.contains("quotaContent")) {
						HSSFCell cell4 = row.createCell(index++);
						cell4.setCellValue(quotaDataDto.getQuotaContent() == null ? "" : quotaDataDto.getQuotaContent());
						cell4.setCellStyle(cellStyle);
					}

					// 单位
					if (headerList.contains("quotaUnit")) {
						HSSFCell cell5 = row.createCell(index++);
						cell5.setCellValue(quotaDataDto.getQuotaUnit() == null ? "" : quotaDataDto.getQuotaUnit());
						cell5.setCellStyle(cellStyle);
					}

					// 权数
					if (headerList.contains("quotaWeight")) {
						HSSFCell cell6 = row.createCell(index++);
						if (quotaDataDto.getQuotaWeight() != null) {
							cell6.setCellValue(quotaDataDto.getQuotaWeight());
						}
						cell6.setCellStyle(cellStyle);
					}

					// 本年度目标
					if (headerList.contains("currentYaerGoal")) {
						HSSFCell cell7 = row.createCell(index++);
						cell7.setCellValue(quotaDataDto.getCurrentYaerGoal() == null ? "" : quotaDataDto.getCurrentYaerGoal());
						cell7.setCellStyle(cellStyle);
					}

					// 考核方式 待定
					if (headerList.contains("assessMethod")) {
						HSSFCell cell8 = row.createCell(index++);
						DictData assessment = DictUtils.getDictData("dc_exam_assessment", quotaDataDto.getAssessMethod());
						if (assessment != null && assessment.getDictLabel() != null) {
							cell8.setCellValue(assessment.getDictLabel());
						}
						cell8.setCellStyle(cellStyle);
					}

					// 上一年度目标任务
					if (headerList.contains("lastYaerGoal")) {
						HSSFCell cell9 = row.createCell(index++);
						cell9.setCellValue(quotaDataDto.getLastYaerGoal() == null ? "" : quotaDataDto.getLastYaerGoal());
						cell9.setCellStyle(cellStyle);
					}

					// 上一年度完成情况
					if (headerList.contains("lastYearComplete")) {
						HSSFCell cell10 = row.createCell(index++);
						cell10.setCellValue(quotaDataDto.getLastYearComplete() == null ? "" : quotaDataDto.getLastYearComplete());
						cell10.setCellStyle(cellStyle);
					}

					// 备注
					if (headerList.contains("remarks")) {
						HSSFCell cell11 = row.createCell(index++);
						DictData remarks = DictUtils.getDictData("dc_exam_remarks", quotaDataDto.getRemarks());
						if (remarks != null && remarks.getDictLabel() != null) {
							cell11.setCellValue(remarks.getDictLabel());
						}
						cell11.setCellStyle(cellStyle);
					}

					// 考核评分单位
					HSSFCell cell12 = row.createCell(index++);
					cell12.setCellValue(quotaDataDto.getGradeOrgName() == null ? "" : quotaDataDto.getGradeOrgName());
					cell12.setCellStyle(cellStyle);
				}
			});
			workbook.write(out);
			out.flush();
			out.close();
			workbook.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 根据传入的数据构造表头
	 * @param headerList
	 * @return
	 */
	private List<String> getHeaderByHeaderList(List<String> headerList) {
		List<String> header = new ArrayList<>();
		header.add("被考核单位");
		if (headerList.contains("quotaType")) {
			header.add("指标类别");
		}
		if (headerList.contains("sortNum")) {
			header.add("序号");
		}
		if (headerList.contains("quotaContent")) {
			header.add("目标内容");
		}
		if (headerList.contains("quotaUnit")) {
			header.add("单位");
		}
		if (headerList.contains("quotaWeight")) {
			header.add("权数");
		}
		if (headerList.contains("currentYaerGoal")) {
			header.add("本年度目标");
		}
		if (headerList.contains("assessMethod")) {
			header.add("考核方式");
		}
		if (headerList.contains("lastYaerGoal")) {
			header.add("上一年度目标任务");
		}
		if (headerList.contains("lastYearComplete")) {
			header.add("上一年度完成情况");
		}
		if (headerList.contains("remarks")) {
			header.add("备注");
		}
		header.add("考核评分单位");
		return header;
	}

	@Transactional(readOnly=false)
	public String saveQuotas(DcSupExamSumQuotaInfo dcSupExamSumQuotaInfo) {
		// 查询指标汇总主表的数据信息
		List<DcSupExamSumQuota> sumQuotas = dcSupExamSumQuotaDao.findAllExamSumQuotas(dcSupExamSumQuotaInfo);
		// 被考核单位
		String[] orgs = dcSupExamSumQuotaInfo.getExameOrg().split(",");
		//被考核单位名称
		String[] orgName = dcSupExamSumQuotaInfo.getExameOrgName().split(",");

		StringBuffer sp =new StringBuffer("以下机构[");
		for (int i = 0; i < orgs.length; i++) {
			DcSupExamSumQuotaInfo query =new DcSupExamSumQuotaInfo();
			query.setSumQuotaId(sumQuotas.get(0).getId());
			query.setQuotaContent(dcSupExamSumQuotaInfo.getQuotaContent());
			query.setExamYear(dcSupExamSumQuotaInfo.getExamYear());
			query.setExameOrg(orgs[i]);

			List<DcSupExamSumQuotaInfo> whetherOrNotTheSame = dao.findList(query);
			if (!CollectionUtils.isEmpty(whetherOrNotTheSame)){
				sp.append("\n");
				sp.append("("+whetherOrNotTheSame.get(0).getExameOrgName() + ")");
			}
		}
		sp.append("]");
		if (sp.toString().length() > 8){
			return sp.append("与当前新增指标目标内容相同").toString();
		}

		// 对数据进行添加
		if (orgs.length > 0 ){

//			//  检查单位指标权数是否大于 100 或者 150 (加分项 和扣分项除外)
			DictData dc_quotaType = DictUtils.getDictData("dc_quotaType", dcSupExamSumQuotaInfo.getQuotaType());

			// 指标类型不等于 加分项 和 倒扣分项 需要进行 指标权数校验  -- 权数校验使用时打开注释即可
//			if (!"13".equals(dc_quotaType.getDictValue())){
//
//				String range = checkQuotaWeigthRange(dcSupExamSumQuotaInfo,dc_quotaType.getDictValue());
//
//				if (range.length() > 8){
//					return range;
//				}
//			}

			// quota_info_id  生成唯一id
			String quotaInfoId = IdGen.nextId();
			// 创建人id
			String userCode = UserUtils.getUser().getUserCode();

			Map<String, List<DcSupExamOrgSelect>> orgSelects = selectDao.findList(new DcSupExamOrgSelect()).stream().collect(Collectors.groupingBy(DcSupExamOrgSelect::getOrgCode));

			for (int i = 0; i < orgs.length; i++) {


				DcSupExamSumQuotaInfo saveData =new DcSupExamSumQuotaInfo();

				// 指标信息数据
				BeanUtils.copyProperties(dcSupExamSumQuotaInfo,saveData);

				// 被考核单位
				saveData.setExameOrg(orgs[i]);
				saveData.setExameOrgName(orgName[i]);
				if (orgSelects.containsKey(saveData.getExameOrg())){
					saveData.setOrgType(orgSelects.get(saveData.getExameOrg()).get(0).getOrgType());
				}
				saveData.setQuotaInfoId(quotaInfoId);
				saveData.setCreateDate(new Date());
				saveData.setCreateBy(userCode);
				// 指标汇总表id
				//saveData.setSumQuotaId(sumQuotas.get(0).getId());
				// 指标类型 、 指标分类分别为 quota_group = 2  quota_class =1
				saveData.setQuotaGroup("2");
				saveData.setQuotaClass("1");
				saveData.setFileStatus("1");
				// 当前版本会存在副本，故需要进行数据插入
				// 存在版本副本时  对应的查询改为 select *  from dc_sup_exam_sum_quota where exam_id =#{examId} and (version_number= #{versionNumber} or remarks4 =#{versionNumber})
				for (int i1 = 0; i1 < sumQuotas.size(); i1++) {
					// 指标汇总表id
					saveData.setSumQuotaId(sumQuotas.get(i1).getId());
					super.save(saveData);

					DcSupExamSumQuotaOrg quotaOrg =new DcSupExamSumQuotaOrg();
					quotaOrg.setSumQuotaId(saveData.getId());
					quotaOrg.setGradeOrg(dcSupExamSumQuotaInfo.getUnitCodes());
					quotaOrg.setGradeOrgName(dcSupExamSumQuotaInfo.getUnitNames());

					dcSupExamSumQuotaOrgDao.insert(quotaOrg);

					// 进行id 置空
					saveData.setId(null);
				}
			}
		}
		return null;
	}

	/**
	 * 检查机构单位权数数值是否超过范围
	 * @return
	 */
	private String checkQuotaWeigthRange(DcSupExamSumQuotaInfo dcSupExamSumQuotaInfo,String quotaType) {
//		&& !dc_quotaType.getDictValue().equals("24")
		// 分组求汇总分数
		List<Map<String, String>> mapList;
		if ("14".equals(quotaType)){
			mapList = dcSupExamSumQuotaDao.groupByOrgSumWeigth(dcSupExamSumQuotaInfo.getExamId(), dcSupExamSumQuotaInfo.getVersionNumber(),"2");
		}else{
			mapList = dcSupExamSumQuotaDao.groupByOrgSumWeigth(dcSupExamSumQuotaInfo.getExamId(), dcSupExamSumQuotaInfo.getVersionNumber(),"1");
		}
		if (mapList ==null){
			mapList =new ArrayList<>();
		}
		// 进行添加前预处理
		StringBuffer sp =new StringBuffer("当前机构以下[");
		for (int i = 0; i < mapList.size(); i++) {
			Map<String, String> map = mapList.get(i);
			// 机构类型
			String orgtype = map.get("orgType");
			// 机构代码
			//String examorg = map.get("examOrg");
			// 机构代码
			String examorgName =  map.get("examOrgName");
			// 分数
		  	Object score2= map.get("score");
		  	Double addScore=0.0;
			if (score2 instanceof BigDecimal){
				BigDecimal add = (BigDecimal) score2;
				addScore = add.doubleValue();
			}
			// 区县
			Double sum= dcSupExamSumQuotaInfo.getQuotaWeight() +addScore;
			if ("14".equals(quotaType)){
				if (sum > 3){
					sp.append( examorgName +"当前加分权重添加前总分数为:(" + addScore +")分,添加后总权数分为:("+sum+")");
				}
			}else{
				if ("1".equals(orgtype) && sum > 150){
					sp.append( examorgName +"[区县]当前加分权重添加前总分数为:("+ addScore +")分,添加后总权数分为:(" + sum +")分");
				}else if ("2".equals(orgtype) && sum >100){
					sp.append( examorgName +"[市直]当前加分权重添加前总分数为:(" + addScore +")分,添加后总权数分为:("+ sum +")分");
				}
			}
		}
		sp.append("]");
		return sp.toString();
	}


	// 指标展示看板 列表
	public Page<ExamQuotaDataDto> quotaResults(ExamQuotaDataDto dcSupExamSumQuotaInfo) {
		Page<ExamQuotaDataDto> page = dcSupExamSumQuotaInfo.getPage();
		// 机构代码
		 Office office = OfficeUtil.getCurrentOffice();
		if (office.getOfficeCode() != null) {
			Office latestUnitByOffice = officeService.getLatestUnitByOffice(office.getOfficeCode());
			dcSupExamSumQuotaInfo.setExameOrg(latestUnitByOffice.getOfficeCode());
		}
		List<ExamQuotaDataDto> quotaInfos = dao.findQuotaResults(dcSupExamSumQuotaInfo);
		return page.setList(quotaInfos);
	}

	public Page<ExamQuotaDataDto> quotaResultsAll(ExamQuotaDataDto dcSupExamSumQuotaInfo) {
		Page<ExamQuotaDataDto> page = dcSupExamSumQuotaInfo.getPage();
		List<ExamQuotaDataDto> quotaInfos = dao.findQuotaResults(dcSupExamSumQuotaInfo);
		return page.setList(quotaInfos);
	}
	/**
	 * 指标展示明细数据
	 * @param dcSupExamSumQuotaInfo
	 * @return
	 */
	public Page<ExamQuotaDataDto> quotaPlayListData(ExamQuotaDataDto dcSupExamSumQuotaInfo) {
		Page<ExamQuotaDataDto> page = dcSupExamSumQuotaInfo.getPage();
		// 机构代码
		String[] quotaType =null;
		if(!StringUtils.isEmpty(dcSupExamSumQuotaInfo.getQuotaTypes())){
			quotaType =dcSupExamSumQuotaInfo.getQuotaTypes().split(",");
			dcSupExamSumQuotaInfo.setTypes(quotaType);
		}
		Office office = OfficeUtil.getCurrentOffice();
		if (office.getOfficeCode() != null) {
			Office latestUnitByOffice = officeService.getLatestUnitByOffice(office.getOfficeCode());
			dcSupExamSumQuotaInfo.setExameOrg(latestUnitByOffice.getOfficeCode());
		}
		dcSupExamSumQuotaInfo.setVersionNumber(null);
		List<ExamQuotaDataDto> examQuotaDataDtoList = dao.quotaPlayListData(dcSupExamSumQuotaInfo);
		return page.setList(examQuotaDataDtoList);
	}
	public List<ExamQuotaDataDto> quotaPlayListDataList(ExamQuotaDataDto examQuotaDataDto){
		return dao.quotaPlayListData(examQuotaDataDto);
	}

	public Page<ExamQuotaDataDto> quotaPlayListData2(ExamQuotaDataDto dcSupExamSumQuotaInfo) {
		Page<ExamQuotaDataDto> page = dcSupExamSumQuotaInfo.getPage();
		// 机构代码
		String[] quotaType =null;
		if(!StringUtils.isEmpty(dcSupExamSumQuotaInfo.getQuotaTypes())){
			quotaType =dcSupExamSumQuotaInfo.getQuotaTypes().split(",");
			dcSupExamSumQuotaInfo.setTypes(quotaType);
		}
		dcSupExamSumQuotaInfo.setExameOrg(dcSupExamSumQuotaInfo.getExameOrg());
		dcSupExamSumQuotaInfo.setVersionNumber(null);
		List<ExamQuotaDataDto> examQuotaDataDtoList = dao.quotaPlayListData(dcSupExamSumQuotaInfo);
		return page.setList(examQuotaDataDtoList);
	}

	@Transactional(readOnly=false)
	public String importData(MultipartFile file, DcSupExamSumQuotaInfo dcSupExamSumQuotaInfo) {
		if (file == null){
			throw new ServiceException(text("请选择导入的数据文件！"));
		}
		AtomicInteger successNum = new AtomicInteger();
		int count = 0;
		int errorCount = 0;
		int errorScore = 0;
		StringBuilder successMsg = new StringBuilder();
		StringBuilder failureMsg = new StringBuilder();
		StringBuffer scoreMsg =new StringBuffer();
		// 获取sheet 页 数据信息
		try (ExcelImport getSheets = new ExcelImport(file.getOriginalFilename(), file.getInputStream());) {
			// 获取当前文档中的 sheet 总数
			int numberOfSheets = getSheets.getWorkbook().getNumberOfSheets();
			// 定义用来装读取excel 数据的容器
			Map<String,List<ExamQuotaDataDto>> pendings =new HashMap<>();
			for (int i = 0; i < numberOfSheets; i++) {
				// 设置 sheet 号  和 标题栏 行数
				getSheets.setSheet(i, 1);
				// 获取 当前sheet页  的数据
				List<ExamQuotaDataDto> dataList = getSheets.getDataList(ExamQuotaDataDto.class);
				// 放置待处理容器集合中
				String sheetName = getSheets.getWorkbook().getSheetAt(i).getSheetName();
				pendings.put(sheetName,dataList);
				count = count + dataList.size();
			}
			// 对数据校验处理
			 Map<String, Object> result = validationData(pendings);
			errorCount = ((List<String>)result.get("error")).size();
			errorScore = ((List<String>)result.get("scoreError")).size();
			failureMsg.append(result.get("error"));
			scoreMsg.append(result.get("scoreError"));
			// 对成功数据进行导入处理
			Map<String,List<ExamQuotaDataDto>> success = (Map<String, List<ExamQuotaDataDto>>) result.get("success");
			// TODO 区县 、市直权数不超过150/100 校验以及加分项指标权数不能超过三分 校验待处理

			if ((errorCount == 0 && errorScore == 0) && !CollectionUtils.isEmpty(success.values())) {
				//----------------- 对数据进行插入处理 -----------------------------
				// 获取最大版本号
				String versionNumber = dcSupExamSumQuotaDao.queryMaxVersionByExamId(dcSupExamSumQuotaInfo.getExamId());
				if (StringUtils.isEmpty(versionNumber)){
					versionNumber="0";
				}
				Long version_num=Long.parseLong(versionNumber) + 1;
				// 获取当前时间
				String versionName = DateUtils.getDate("yyyyMMddHHmm_" + versionNumber);
				// 当前操作人信息
				String userCode = UserUtils.getUser().getUserCode();
				// 考核任务指标汇总表-主表  数据添加
				DcSupExamSumQuota save = DcSupExamSumQuota.builder()
						.examId(dcSupExamSumQuotaInfo.getExamId())
						.versionNumber(version_num)
						.versionName(versionName)
						.sumStatus("1")
						.fileStatus("1")
						.build();
				save.setCreateDate(new Date());
				save.setCreateBy(userCode);
				// 保存数据
				dcSupExamSumQuotaDao.insert(save);

				// 指标内容相同时  id为 相同
				Map<String,String> contentIds =new HashMap<>();

				success.forEach((key, value) -> {
					for (int i = 0; i < value.size(); i++) {
						ExamQuotaDataDto dataDto = value.get(i);

						DcSupExamSumQuotaInfo newData = new DcSupExamSumQuotaInfo();

						BeanUtils.copyProperties(dataDto, newData);
						String content = dataDto.getQuotaType() +dataDto.getQuotaContent()+dataDto.getGradeOrg();
						if (contentIds.containsKey(content)){
							newData.setQuotaInfoId(contentIds.get(content));
						}else{
							String nextId = IdGen.nextId();
							newData.setQuotaInfoId(nextId);
							contentIds.put(content,nextId);
						}
						newData.setSumQuotaId(save.getId());
						newData.setCreateDate(new Date());
						newData.setCreateBy(userCode);
						newData.setExamYear(dcSupExamSumQuotaInfo.getExamYear());

						dao.insert(newData);
						// 插入 考核任务指标汇总表-牵头评分单位  dc_sup_exam_sum_quota_org
						DcSupExamSumQuotaOrg saveOrg = new DcSupExamSumQuotaOrg();
						// 关键指标  评分单位为  考核
						if ("1".equals(dataDto.getQuotaGroup()) && "1".equals(dataDto.getQuotaClass())){
							saveOrg.setGradeOrgName("市政府办公室");
							saveOrg.setGradeOrg("263");
						}else{
							saveOrg.setGradeOrgName(dataDto.getGradeOrgName());
							saveOrg.setGradeOrg(dataDto.getGradeOrg());
						}
						saveOrg.setSumQuotaId(newData.getId());

						dcSupExamSumQuotaOrgDao.insert(saveOrg);
						successNum.getAndIncrement();
					}
				});
				List<DcSupExamQuotaOrg> list = dcSupExamQuotaOrgService.findOrgByExamId(dcSupExamSumQuotaInfo.getExamId());
				StringBuffer info_result = new StringBuffer();
				if (!CollectionUtils.isEmpty(list)){
					info_result.append(version_num + "-" + list.get(0).getExameOrg());
				}else{
					info_result.append(version_num + "-" + "success");
				}
				successMsg.append(info_result.toString() +"&"+"导入成功，请在新生成的版本中查看导入数据 ,成功导入数据共 " + successNum + " 条;\n" );
			}
		} catch (Exception e) {
			 e.printStackTrace();
			 failureMsg.append("导入数据出现错误,"+e.getMessage());
			throw new ServiceException(failureMsg.toString());
		 }
		successMsg.append("共读取"+count+"条数据" );
		if (errorCount >0){
			successMsg.append("数据格式不正确的共" +errorCount +"条,错误如下:\n" + failureMsg);
		}
		if (errorScore > 0){
			successMsg.append("导入[数据权数]不正确的共" +errorScore +"条,错误如下:\n" + scoreMsg);
		}
		return successMsg.toString();
	}

	/**
	 * 数据校验
	 * @param pendings
	 */
	public Map<String,Object> validationData(Map<String,List<ExamQuotaDataDto>> pendings){
		// {"被考核单位","指标类别","序号","目标内容","单位","权数","本年度目标","考核方式","上一年度目标任务","上一年度完成情况","备注","考核评分单位"}
		// 成功数据信息
		Map<String,List<ExamQuotaDataDto>> success =new HashMap<>();
		// 错误数据信息
		List<String> error =new ArrayList<>();
		// 数据中权数总分问题
		List<String> scoreError =new ArrayList<>();

		// 查询所有机构名称 --- 机构名称
		Map<String, List<DcSupExamOrgSelect>> orgSelects = selectDao.findList(new DcSupExamOrgSelect()).stream().collect(Collectors.groupingBy(DcSupExamOrgSelect::getOrgName));
        // 机构别名
        Map<String, List<DcSupExamOrgSelect>> orgSelectsAliasName = selectDao.findList(new DcSupExamOrgSelect()).stream().collect(Collectors.groupingBy(DcSupExamOrgSelect::getAliasName));


        pendings.forEach((k,v)->{
			// sheet 页名称
			 String sheetName = k;
			// 数据信息
			List<ExamQuotaDataDto> quotaDataDto = v;
			// 返回数据信息
			List<ExamQuotaDataDto> successData =new ArrayList<>();
			// 指标内容 记录是否存在
			Set<String> recordsAre= new HashSet<>();

			for (int i = 0; i < quotaDataDto.size(); i++) {
				ExamQuotaDataDto validation = quotaDataDto.get(i);
				StringBuffer sb =new StringBuffer("");
				// 被考核单位
				if (StringUtils.isEmpty(validation.getExameOrgName())){
					sb.append(sheetName +"工作簿 第"+(i+1)+"行[被考核单位]数据为空;" );
				}else{
					if (orgSelects.containsKey(validation.getExameOrgName().trim())){
						 DcSupExamOrgSelect orgSelect = orgSelects.get(validation.getExameOrgName().trim()).get(0);
						validation.setExameOrg(orgSelect.getOrgCode());
						validation.setExameOrgName(orgSelect.getOrgName());
						// 区县类型
						validation.setOrgType(orgSelect.getOrgType());
					}else{
					    if (orgSelectsAliasName.containsKey(validation.getExameOrgName().trim())){
                            DcSupExamOrgSelect orgSelect = orgSelectsAliasName.get(validation.getExameOrgName().trim()).get(0);
                            validation.setExameOrg(orgSelect.getOrgCode());
                            validation.setExameOrgName(orgSelect.getOrgName());
                            // 区县类型
                            validation.setOrgType(orgSelect.getOrgType());
                        }else{
                            sb.append(sheetName +"工作簿 第"+(i+1)+"行[被考核单位]数据 单位名称未匹配;" );
                        }
					}
				}
				// 指标类别
				if (StringUtils.isEmpty(validation.getQuotaType())){
					sb.append(sheetName +"工作簿 第"+(i+1)+"行[指标类别]数据为空或类别不匹配;" );
				}else{
					// 字典数据查找对应的类型
					String quotaType = validationChooseOption(validation.getQuotaType(), "dc_quotaType");
					if ("9999".equals(quotaType)){
						sb.append(sheetName +"工作簿 第"+(i+1)+"行[指标类别]参数存在异常;" );
					}else{
						validation.setQuotaType(quotaType);
						// 倒扣分
						if ("13".equals(quotaType)){
						validation.setQuotaClass("3");
						validation.setQuotaGroup("2");
						// 加分项
						}else if ("14".equals(quotaType)){
							validation.setQuotaClass("2");
							validation.setQuotaGroup("2");
						// 单项指标
						}else if ("11".equals(quotaType)){
							validation.setQuotaClass("1");
							validation.setQuotaGroup("2");
						}else{
							validation.setQuotaClass("1");
							validation.setQuotaGroup("1");
						}
					}
				}
				// 序号
				if (validation.getSortNum() == null){
					sb.append(sheetName +"工作簿 第"+(i+1)+"行[序号]数据为空;" );
				}else{
					if (validation.getSortNum() < 1){
						sb.append(sheetName +"工作簿 第"+(i+1)+"行[序号] 小于 1;" );
					}
				}
				// 目标内容
				if (StringUtils.isEmpty(validation.getQuotaContent())){
					sb.append(sheetName +"工作簿 第"+(i+1)+"行[目标内容]数据为空;" );
				}
				// 权数
				if (validation.getQuotaWeight() == null){
					sb.append(sheetName +"工作簿 第"+(i+1)+"行[权数]数据为空;" );
				}else{
					if (validation.getQuotaWeight() == 0){
						sb.append(sheetName +"工作簿 第"+(i+1)+"行[权数]数据为 0;" );
					}
				}
				// 本年度目标
				if (validation.getQuotaClass() != null && "1".equals(validation.getQuotaClass()) && StringUtils.isEmpty(validation.getCurrentYaerGoal())){
					sb.append(sheetName +"工作簿 第"+(i+1)+"行[本年度目标]数据为空;" );
				}
				// 考核方式
				if (!StringUtils.isEmpty(validation.getAssessMethod())){
					//sb.append(sheetName +"工作簿 第"+(i+1)+"行[考核方式]数据为空;" );
				//}else{
//					DictData assessment = DictUtils.getDictData("dc_exam_assessment", validation.getAssessMethod());
					String assessMethod = validationChooseOption(validation.getAssessMethod().trim(), "dc_exam_assessment");
					if (assessMethod == null){
						sb.append(sheetName +"工作簿 第"+(i+1)+"行[考核方式]参数存在异常,期望数据格式为:[实地考核、日常考核];" );
					}else{
						validation.setAssessMethod(assessMethod);
					}
				}
				// 备注
				if (StringUtils.isEmpty(validation.getRemarks())){
					sb.append(sheetName +"工作簿 第"+(i+1)+"行[备注]数据为空;" );
				}else{
					 String dcExamRemarks = validationChooseOption(validation.getRemarks().trim(), "dc_exam_remarks");
					 if ("9999".equals(dcExamRemarks)){
						 sb.append(sheetName +"工作簿 第"+(i+1)+"行[备注]参数存在异常,期望数据格式为:[延续、新增、调整];" );
					 }else{
						validation.setRemarks(dcExamRemarks);
					 }
				}
				// 考核评分单位
				if (StringUtils.isEmpty(validation.getGradeOrgName())){
					sb.append(sheetName +"工作簿 第"+(i+1)+"行[考核评分单位]数据为空;" );
				}else{
					if (orgSelects.containsKey(validation.getGradeOrgName().trim())){
						 validation.setGradeOrg(orgSelects.get(validation.getGradeOrgName().trim()).get(0).getOrgCode());
					}else if (orgSelectsAliasName.containsKey(validation.getGradeOrgName().trim())){
						final List<DcSupExamOrgSelect> selects = orgSelectsAliasName.get(validation.getGradeOrgName().trim());
						validation.setGradeOrg(selects.get(0).getOrgCode());
					} else{
						sb.append(sheetName +"工作簿 第"+(i+1)+"行[考核评分单位]数据 单位名称未匹配;" );
					}
				}
				// 查看目标内容是否已经存在
				if (recordsAre.contains(validation.getQuotaContent().trim())){
					sb.append(sheetName +"工作簿 第"+(i+1)+"行[目标内容]存在重复;");
				}else{
					recordsAre.add(validation.getQuotaContent().trim());
				}

				if (sb.length() > 8){
					error.add(sb.toString());
				}else{
					successData.add(validation);
				}
			}
//			if (!CollectionUtils.isEmpty(successData)){
//				// 获取 关键指标 和单项指标
//				List<ExamQuotaDataDto> quotaDataDtos = successData.stream().filter(s -> "1".equals(s.getQuotaClass()) && ("2".equals(s.getQuotaGroup()) || "1".equals(s.getQuotaGroup()))).collect(Collectors.toList());
//				// 获取加分指标
//				List<ExamQuotaDataDto> addDtoStream = successData.stream().filter(s -> "2".equals(s.getQuotaClass())).collect(Collectors.toList());
//				// 关键指标总分数
//				double sum = quotaDataDtos.stream().mapToDouble(ExamQuotaDataDto::getQuotaWeight).sum();
//				// 加分指标总分数
//				double add = addDtoStream.stream().mapToDouble(ExamQuotaDataDto::getQuotaWeight).sum();
//				StringBuffer sp = new StringBuffer();
//				if (add > 3) {
//					sp.append(sheetName + "当前加分权重添加总分数为:(" + add+")");
//				}
//				if (sum > 100) {
//					ExamQuotaDataDto dataDto = quotaDataDtos.get(0);
//					if (dataDto.getOrgType() == null){
//						sp.append(sheetName + "区县类型有误");
//					}else{
//						if ("1".equals(dataDto.getOrgType()) && sum > 150) {
//							sp.append(sheetName + "[区县]当前加分权重添加总分数为:(" + sum + ")");
//						} else if ("2".equals(dataDto.getOrgType()) && sum > 100) {
//							sp.append(sheetName + "[市直]当前加分权重添加总分数为:(" + sum + ")");
//						}
//					}
//				}
//				if (sp.length() < 8){
//					// 数据组装返回
					success.put(k,successData);
//				}else{
//					scoreError.add(sp.toString());
//				}
//			}

		});
		Map<String,Object> result =new HashMap<>();
		result.put("success",success);
		result.put("error",error);
		result.put("scoreError",scoreError);
		return result;
	}

	/**
	 * 查询数据是否在字典中
	 * @param option 数据
	 * @param dicType 字典类型
	 * @return
	 */
	public String validationChooseOption(String option,String dicType){
		 DictData data = DictUtils.getDictData(dicType, option);
		 if (data == null){
			 List<DictData> dictList = DictUtils.getDictList(dicType);
			 if (dictList !=null){
			 	  List<DictData> dictData = dictList.stream().filter(s -> s.getDictLabel().equals(option)).collect(Collectors.toList());
				  return CollectionUtils.isEmpty(dictData)?"9999":dictData.get(0).getDictValue();
			 }
		 }
		return data == null ?"9999":data.getDictValue();
	}

	public List<Map<String, Object>> selectOrgs(String excludeCode) {
		List<Map<String, Object>> mapList = ListUtils.newArrayList();
		List<DcSupExamOrgSelect> selectDaoList = selectDao.findList(new DcSupExamOrgSelect());
		if (!CollectionUtils.isEmpty(selectDaoList)){
			for (int i = 0; i < selectDaoList.size(); i++) {
				Map<String,Object> result =new HashMap<>();
				 DcSupExamOrgSelect orgSelect = selectDaoList.get(i);
				 if(StringUtils.equals(excludeCode,orgSelect.getOrgCode())){
				 	continue;
				 }
				result.put("id",orgSelect.getOrgCode());
				result.put("pId","0");
				result.put("code",orgSelect.getOrgCode());
				result.put("name",orgSelect.getOrgName());
				result.put("title",orgSelect.getOrgName());
				result.put("isParent",false);
				mapList.add(result);
			}
		}
		return mapList;
	}

	public Page<DcSupExamSumQuotaInfo> findSinglePage(DcSupExamSumQuotaInfo dcSupExamSumQuotaInfo) {
		Page<DcSupExamSumQuotaInfo> page = dcSupExamSumQuotaInfo.getPage();
		List<DcSupExamSumQuotaInfo>   list = dao.findSinglePage(dcSupExamSumQuotaInfo);
		page.setList(list);
		return page;
	}

	public Page<DcSupExamSumQuotaInfo> findSingleOrgPage(DcSupExamSumQuotaInfo dcSupExamSumQuotaInfo) {
		Page<DcSupExamSumQuotaInfo> page = dcSupExamSumQuotaInfo.getPage();
		List<DcSupExamSumQuotaInfo>   list = dao.findSingleOrgPage(dcSupExamSumQuotaInfo);
		page.setList(list);
		return page;
	}

	public Page<DcSupExamDetailFile> listDetailFileData(DcSupExamDetailFile dcSupExamSumQuotaInfo) {
		Page<DcSupExamDetailFile> page = dcSupExamSumQuotaInfo.getPage();
		List<DcSupExamDetailFile>   list = dao.listDetailFileData(dcSupExamSumQuotaInfo);
		page.setList(list);
		return page;
	}

	public void saveStrFile(List<DcSupExamDetailFile> dcSupExamSumQuotaInfos,String noticeId) {
		for(DcSupExamDetailFile file:dcSupExamSumQuotaInfos){
			String[] ids = file.getIds().split(",");
			String detailFile = IdGen.nextId();
			for(String id:ids ){
				dao.updateFileStatusDetail(id,detailFile,UserUtils.getUser().getUserCode());
			}
			FileUploadUtils.saveFileUpload(detailFile, "dcSupExamSumQuotaInfo_file", file.getFileuploadId(), "");
		}
		DcSupExamNotice dcSupExamNotice = dcSupExamNoticeService.get(noticeId);
		Office latestUnitByOffice = sysOfficeUnitService.getLatestUnitByOffice();
		//提交细则报送时把细则通知设置为已办
		dcSupBacklogService.doBacklog(dcSupExamNotice.getExamId(),"exam_submit_xize",latestUnitByOffice.getOfficeCode());

		new Thread(()-> {
			User user  = new User();
			user.setRoleCode("OTS_ORG");
			user.setUserType("employee");
			user.setUserCode(dcSupExamNotice.getCreateBy());
			List<User> list = userService.findList(user);
			String msg = "";
			String bizType="";

				msg=latestUnitByOffice.getOfficeName()+"报送单位的细则已补充，待审核，请及时登录系统查看";
				bizType="exam_audit_xize";
			for(User user_ : list){
				//处理发信息逻辑
//				PcMsgContent pcMsgContent = new PcMsgContent();
//				pcMsgContent.setTitle("提示信息");
//				pcMsgContent.setContent(msg);
//				MsgPushUtils.push(pcMsgContent, dcSupExamSumQuotaInfos.get(0).getSumQuotaId(), bizType, user_.getUserCode());
				//发送易政网消息
				MsgDetail msgDetail = new MsgDetail();
				msgDetail.setSendid(UserUtils.getUser().getUserCode());
				msgDetail.setSubjectid(user_.getUserCode());
				msgDetail.setMesg(msg);
				lehandYzwPushTask.pushScoreShortMsg(msgDetail);
				dcSupBacklogService.add("目标考核","细则审核","单项指标细则报送审核","提示信息"
						,msg.replace("登录系统","")
						,"/a/targetAudit/targetAuditPage?examId="+dcSupExamNotice.getExamId()+"&examTitle="+dcSupExamNotice.getExamTitle(),latestUnitByOffice.getOfficeCode()
						,dcSupExamNotice.getExamId(),bizType,user.getUserCode()
						,"","");
			}
		}).start();

	}

	public List<DcSupExamSumQuotaInfo> findDcSupExamSumQuotaInfoList(DcSupExamSumQuotaInfo dcSupExamSumQuotaInfo) {
		return this.dao.findDcSupExamSumQuotaInfoList(dcSupExamSumQuotaInfo);
	}

	public List<DcSupExamSumQuotaInfo> findReleaseDcSUpExamSumQuotaInfo(DcSupExamSumQuotaInfo dcSupExamSumQuotaInfo) {
		return this.dao.findReleaseDcSUpExamSumQuotaInfo(dcSupExamSumQuotaInfo);
	}

	/**
	 *
	 * @param examId
	 * @param examYear
	 * @return
	 */
	public String isExistNoAudit(String examId, String examYear) {
		// 关键指标
		List<Map<String, String>> hingeQuota=targetAuditDao.exameSendOrgListData(null, "1", examYear, examId);
		// 单项指标
		List<Map<String, String>> singleQuota=targetAuditDao.exameSendOrgListData(null, "2", examYear, examId);
		Integer result = 0;
		if(!hingeQuota.isEmpty()){
			for (int i = 0; i < hingeQuota.size(); i++) {
				if(hingeQuota.get(i).get("submitstatus").contains(",")){
					String[] s=hingeQuota.get(i).get("submitstatus").split(",");
					 if(!"4".equals(s[0])){
						 result = result +2;
					 	break;
					 }
				}
			}
		}
		if(!singleQuota.isEmpty()){
			for (int i = 0; i < singleQuota.size(); i++) {
				if(singleQuota.get(i).get("submitstatus").contains(",")){
					String[] s=singleQuota.get(i).get("submitstatus").split(",");
					if(!"4".equals(s[0])){
						result = result +3;
						break;
					}
				}
			}
		}
		if (result == 5){
			return  "1";
		}else if (result == 2){
			return "2";
		}else if (result == 3){
			return "3";
		}else{
			return "99";
		}
	}

	public List<Map<String, Object>> chooseOrgs(String examId) {
		List<DcSupExamQuotaOrg> byExamId = dcSupExamQuotaOrgDao.findOrgByExamId(examId);
		List<Map<String, Object>> mapList = ListUtils.newArrayList();
		if (!CollectionUtils.isEmpty(byExamId)){
			for (int i = 0; i < byExamId.size(); i++) {
				Map<String,Object> result =new HashMap<>();
				DcSupExamQuotaOrg orgSelect = byExamId.get(i);
				result.put("id",orgSelect.getExameOrg());
				result.put("pId","0");
				result.put("code",orgSelect.getExameOrg());
				result.put("name",orgSelect.getExameOrgName());
				result.put("title",orgSelect.getExameOrgName());
				result.put("isParent",false);
				mapList.add(result);
			}
		}
		return mapList;
	}

	// 根据版本去查询考核评分单位信息
	public List<DcSupExamSumQuotaInfo> getAssessOrganization(DcSupExamSumQuotaInfo dcSupExamSumQuotaInfo) {
		List<DcSupExamSumQuotaInfo> list=dcSupExamQuotaOrgDao.getAssessOrganization(dcSupExamSumQuotaInfo);
		return list;
	}

	public Page<DcSupExamSumQuotaInfo> quotaPageList(DcSupExamSumQuotaInfo dcSupExamSumQuotaInfo) {
		List<DcSupExamSumQuotaInfo> list= dcSupExamQuotaOrgDao.quotaPageList(dcSupExamSumQuotaInfo);
		return dcSupExamSumQuotaInfo.getPage().setList(list);
	}

	public Page<DcSupExamSumQuotaInfo> listOrgByQuota(DcSupExamSumQuotaInfo dcSupExamSumQuotaInfo) {
		List<DcSupExamSumQuotaInfo> list= dcSupExamQuotaOrgDao.listOrgByQuota(dcSupExamSumQuotaInfo);
		return dcSupExamSumQuotaInfo.getPage().setList(list);
	}

	@Transactional(readOnly = false)
	public String updateQuotaContent(DcSupExamSumQuotaInfo dcSupExamSumQuotaInfo) {
		List<DcSupExamSumQuotaInfo> quotaInfos = dcSupExamQuotaOrgDao.checkQuotaContent(dcSupExamSumQuotaInfo);
		if (!CollectionUtils.isEmpty(quotaInfos)&&quotaInfos.size()>1) {
			return "目标内容存在重复或修改失败";
		}
		switch (dcSupExamSumQuotaInfo.getQuotaType()){
			case "11":
				dcSupExamSumQuotaInfo.setQuotaClass("1");
				break;
			case "14":
				dcSupExamSumQuotaInfo.setQuotaClass("2");
				break;
			case "13":
				dcSupExamSumQuotaInfo.setQuotaClass("3");
				break;
		}
		dcSupExamSumQuotaInfo.setExameOrg(dcSupExamSumQuotaInfo.getGradeOrg());
		List<DcSupExamSumQuotaInfo> list = dcSupExamQuotaOrgDao.listOrgByQuota(dcSupExamSumQuotaInfo);
		List<String> collect = list.stream().map(s -> s.getId()).collect(Collectors.toList());
		//删除sumInfo表  删除评分单位sumOrg
		if(dao.deleteSumInfo(collect)!=dao.deleteSumOrg(collect)){
			throw new ServiceException("修改失败，联系管理员");
		}
		String exameOrgs = dcSupExamSumQuotaInfo.getExameOrgs();
		String exameOrgNames = dcSupExamSumQuotaInfo.getExameOrgNames();
		String[] orgs = exameOrgs.split(",");
		String[] orgNames = exameOrgNames.split(",");
		for (int i = 0; i < orgs.length; i++) {
			dcSupExamSumQuotaInfo.setId(IdGen.nextId());
			dcSupExamSumQuotaInfo.setExameOrg(orgs[i]);
			dcSupExamSumQuotaInfo.setExameOrgName(orgNames[i]);
			dcSupExamSumQuotaInfo.setQuotaGroup("2");
			dcSupExamSumQuotaInfo.setQuotaContent(dcSupExamSumQuotaInfo.getRemarks2());
			DcSupExamOrgSelect org_ = dcSupExamOrgSelectDao.getOrgByName(orgNames[i]);
			dcSupExamSumQuotaInfo.setOrgType(org_.getOrgType());
			dao.insert(dcSupExamSumQuotaInfo);
			DcSupExamSumQuotaOrg org = new DcSupExamSumQuotaOrg();
			org.setId(dcSupExamSumQuotaInfo.getId());
			org.setSumQuotaId(dcSupExamSumQuotaInfo.getId());
			org.setGradeOrg(dcSupExamSumQuotaInfo.getGradeOrg());
			org.setGradeOrgName(dcSupExamSumQuotaInfo.getGradeOrgName());
			dcSupExamSumQuotaOrgDao.insert(org);
		}

		return "ok";
	}

	private boolean checkDataIsNull(DcSupExamSumQuotaInfo dcSupExamSumQuotaInfo) {
		if (StringUtils.isEmpty(dcSupExamSumQuotaInfo.getRemarks2())
		 && dcSupExamSumQuotaInfo.getSortNum() ==null
				&& StringUtils.isEmpty(dcSupExamSumQuotaInfo.getQuotaUnit())
				&& dcSupExamSumQuotaInfo.getQuotaWeight() ==null
				&& StringUtils.isEmpty(dcSupExamSumQuotaInfo.getCurrentYaerGoal())
				&& StringUtils.isEmpty(dcSupExamSumQuotaInfo.getLastYaerGoal())
				&& StringUtils.isEmpty(dcSupExamSumQuotaInfo.getLastYearComplete())
				&& StringUtils.isEmpty(dcSupExamSumQuotaInfo.getAssessMethod())
				&& StringUtils.isEmpty(dcSupExamSumQuotaInfo.getRemarks())
		){
			return false;
		}
		return true;
	}

	public String getDanWei(DcSupExamSumQuotaInfo dcSupExamSumQuotaInfo,String type) {
		List<DcSupExamSumQuotaInfo> list = dcSupExamQuotaOrgDao.listOrgByQuota(dcSupExamSumQuotaInfo);
		if (CollectionUtils.isEmpty(list)) {
			return "";
		}
		if("code".equals(type)){
			return list.stream().map(s -> s.getExameOrg()).collect(Collectors.joining(","));
		}
		return list.stream().map(s -> s.getExameOrgName()).collect(Collectors.joining(","));

	}
	@Transactional(readOnly=false)
	public String introQuotaInfo(DcSupExamSumQuota dcSupExamSumQuota) {
		Map<String, List<DcSupExamOrgSelect>> orgSelects = selectDao.findList(new DcSupExamOrgSelect()).stream().collect(Collectors.groupingBy(DcSupExamOrgSelect::getOrgCode));
		DcSupExamSumQuota dcSupExamSumQuotaDb = dcSupExamSumQuotaDao.getByEntity(dcSupExamSumQuota);

		if (dcSupExamSumQuota.getVersionNumber() != null && !"2".equals(dcSupExamSumQuotaDb.getSumStatus()) ){
			List<ExamQuotaCopyDto>	list = dcSupExamQuotaDao.queryQuotaByParam(dcSupExamSumQuotaDb);
			//创建主版本1号，
			if(list!=null && list.size()>0) {
				dcSupExamSumQuotaDb.setUpdateDate(new Date());
				dcSupExamSumQuotaDao.update(dcSupExamSumQuotaDb);
				for (ExamQuotaCopyDto dto : list) {
					DcSupExamSumQuotaInfo info = new DcSupExamSumQuotaInfo();
					BeanUtils.copyProperties(dto, info);
					info.setId(IdGen.nextId());
					info.setQuotaWeight(dto.getQuotaWeight());
					info.setSumQuotaId(dcSupExamSumQuotaDb.getId());
					info.setQuotaInfoId(dto.getId());
					// 区县类型
					if (StringUtils.isEmpty(dto.getOrgType())) {
						if (orgSelects.containsKey(dto.getExameOrg())) {
							info.setOrgType(orgSelects.get(dto.getOrgType()).get(0).getOrgType());
						}
					}
					if (StringUtils.equals(dto.getQuotaGroup(), "2")) {
						DcSupExamSumQuotaOrg org = new DcSupExamSumQuotaOrg();
						org.setSumQuotaId(info.getId());
						String id = IdGen.nextId();
						org.setId(id);
						org.setSumQuotaId(info.getId());
						org.setGradeOrg(dto.getCreateOrg());
						org.setGradeOrgName(dto.getCreateOrgName());
						dcSupExamSumQuotaOrgDao.insert(org);
					}
					if (StringUtils.equals(dto.getQuotaGroup(), "1")) {
						DcSupExamSumQuotaOrg org = new DcSupExamSumQuotaOrg();
						org.setSumQuotaId(info.getId());
						String id = IdGen.nextId();
						org.setId(id);
						org.setSumQuotaId(info.getId());
						org.setGradeOrg("263");
						org.setGradeOrgName("市政府办公室");
						dcSupExamSumQuotaOrgDao.insert(org);
					}
					info.setFileStatus("1");
					dao.insert(info);
				}
			}
		}
		return "";
	}

	public GroupByTypeCount groupByQuotaTypeCount(ExamQuotaDataDto dcSupExamSumQuotaInfoQuery) {
		List<Map<String, Object>> mapList = dao.groupByQuotaTypeCount(dcSupExamSumQuotaInfoQuery);
		GroupByTypeCount result =new GroupByTypeCount();
		if (!CollectionUtils.isEmpty(mapList)) {
			AtomicReference<Double> key = new AtomicReference<>(0d);
				mapList.stream().forEach(k->{
					BigDecimal value = new BigDecimal(String.valueOf(k.get("summary")));
					value.setScale(2);
					if ( k.get("type").equals("11") ){
						result.setTotalWeight(value);
					}else if (k.get("type").equals("13")){
						result.setReverseScore(value);
					}else if (k.get("type").equals("14")){
						result.setWeightedScore(value);
					}else {
						key.updateAndGet(v -> new Double((double) (v + value.doubleValue())));

					}
				});

			result.setKeyWeight(BigDecimal.valueOf(key.get()));
		}
		return result;
	}

	public List<ExamQuotaDataExport> exportQuotaPlayListData2(ExamQuotaDataDto dcSupExamSumQuotaInfo) {
		String[] quotaType =null;
		if(!StringUtils.isEmpty(dcSupExamSumQuotaInfo.getQuotaTypes())){
			quotaType =dcSupExamSumQuotaInfo.getQuotaTypes().split(",");
			dcSupExamSumQuotaInfo.setTypes(quotaType);
		}
		dcSupExamSumQuotaInfo.setExameOrg(dcSupExamSumQuotaInfo.getExameOrg());
		dcSupExamSumQuotaInfo.setVersionNumber(null);
		List<ExamQuotaDataDto> examQuotaDataDtoList = dao.quotaPlayListData(dcSupExamSumQuotaInfo);
		List<ExamQuotaDataExport> collect = examQuotaDataDtoList.stream().map(e -> {
			ExamQuotaDataExport data = new ExamQuotaDataExport();
			BeanUtils.copyProperties(e, data);
			return data;
		}).collect(Collectors.toList());
		return collect;
	}

	public DcSupExamSumQuotaInfo listOrgByQuotaOne(DcSupExamSumQuotaInfo dcSupExamSumQuotaInfo) {
		List<DcSupExamSumQuotaInfo> list = dcSupExamQuotaOrgDao.listOrgByQuota(dcSupExamSumQuotaInfo);
		if(list!=null && list.size()>0){
			return list.get(0);
		}
		return null;
	}
	@Transactional(readOnly=false)
	public String delSumInfo(DcSupExamSumQuotaInfo dcSupExamSumQuotaInfo) {
		List<DcSupExamSumQuotaInfo> list = dcSupExamQuotaOrgDao.listOrgByQuota(dcSupExamSumQuotaInfo);
		List<String> collect = list.stream().map(s -> s.getId()).collect(Collectors.toList());
		//删除sumInfo表  删除评分单位sumOrg
		if(dao.deleteSumInfo(collect)!=dao.deleteSumOrg(collect)){
			throw new ServiceException("删除失败，联系管理员");
		}
		return "ok";
	}
	@Transactional(readOnly=false)
	public String updateSumOrg(DcSupExamSumQuotaInfo dcSupExamSumQuotaInfo1) {
		super.save(dcSupExamSumQuotaInfo1);
		return "ok";
	}
}